package com.clss.commandhelper.function.homefragment2nd;

import com.clss.commandhelper.base.BaseJson;
import com.clss.commandhelper.base.BasePresenter;
import com.clss.commandhelper.base.BaseView;
import com.clss.commandhelper.tools.Constant;
import com.clss.commandhelper.tools.eventbus.EventBusHelper;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 * @author liuv
 * @date 2017/12/5
 */

public class Home2ndPresenter extends BasePresenter {
    private static final String TAG = "Home2ndPresenter";

    private Home2ndView mHome2ndView;
    private Home2ndModel mHome2ndModel;
    private int mPage;

    public void setHome4thView(Home2ndView home2ndView) {
        this.mHome2ndView = home2ndView;
    }

    public void getClueList(){
        if (mHome2ndModel == null){
            mHome2ndModel = new Home2ndModel(mHome2ndView.getActContext());
        }
        mHome2ndModel.getClueList(mPage, new Callback<BaseJson>() {
            @Override
            public void onResponse(Call<BaseJson> call, Response<BaseJson> response) {
                mHome2ndView.dismissLoadingDialog();
                BaseJson baseJson = response.body();
                EventBusHelper.handleBaseJson(baseJson);
                if (baseJson != null){
                    if (baseJson.getCode() != 0){
                        if (baseJson.getCode() == EventBusHelper.NO_MORE_DATA){
                            mHome2ndView.getClueListSuccess(new ArrayList<ClueEntity>());
                        }
                        mHome2ndView.responseError(baseJson.getCode(), baseJson.getError());
                    }else {
                        List<ClueEntity> clueEntityList;
                        Type typeToken = new TypeToken<List<ClueEntity>>(){}.getType();
                        if (null == baseJson.getList()){
                            mHome2ndView.responseError(baseJson.getCode(), baseJson.getError());
                        }else {
                            clueEntityList = mGson.fromJson(baseJson.getList().toString(), typeToken);
                            mHome2ndView.getClueListSuccess(clueEntityList);
                        }
                    }
                }else {
                    mHome2ndView.responseError(Constant.UNKNOW_ERROR_CODE, Constant.UNKNOW_ERROR_MESSAGE);
                }
            }

            @Override
            public void onFailure(Call<BaseJson> call, Throwable t) {
                mHome2ndView.dismissLoadingDialog();
                mHome2ndView.requestFailure(t);
            }
        });
    }

    @Override
    public void cancelCall() {

    }

    interface Home2ndView extends BaseView{
        void getClueListSuccess(List<ClueEntity> clueEntityList);

    }
}
